//
//  BTEOrderSubViewController.swift
//  BTE
//
//  Created by 张文 on 2025/8/30.
//

import UIKit

enum OrderType: Int {
    case actor = 4
    case borrowing = 7
    case consuming = 6
    case packages = 5
}

class BTEOrderSubViewController: UIViewController {
    
    var clickItem:((String)->())?
    
    var clickPro:((String)->())?
    
    var model: [BTEProductpenalosavincentsNetModel]? {
        didSet {
            guard let m = model else {
                list.empty.hidden()
                list.empty.show(emptyImage: UIImage.init(named: "花瓣素材_手绘-毕业装饰贴纸2-纸飞机_48171736 1")!,
                                             emptyTitle: BTELanguageManager.shared.localizedString(forKey:"no order yet"),
                                 buttonTitle: BTELanguageManager.shared.localizedString(forKey:"Go to Apply"),
                                             offsetY: -90,
                                                  canBunces: true) {
                    if  let windowScene = UIApplication.shared.connectedScenes
                        .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene,
                          let rootVC = windowScene.windows.first(where: { $0.isKeyWindow })?.rootViewController  as? UITabBarController {
                        rootVC.selectedIndex = 0
                        (rootVC as! BTEBaseTabBarController).basetabbar.la.image = UIImage.init(named: "gwerger432323232")
                        (rootVC as! BTEBaseTabBarController).basetabbar.ed.image = UIImage.init(named: "fwef32323232er23")
                    }
                        }
                return
            }
            
            if m.count == 0 {
                list.empty.hidden()
                list.empty.show(emptyImage: UIImage.init(named: "花瓣素材_手绘-毕业装饰贴纸2-纸飞机_48171736 1")!,
                                             emptyTitle: BTELanguageManager.shared.localizedString(forKey:"no order yet"),
                                 buttonTitle: BTELanguageManager.shared.localizedString(forKey:"Go to Apply"),
                                             offsetY: -90,
                                                  canBunces: true) {
                    if  let windowScene = UIApplication.shared.connectedScenes
                        .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene,
                          let rootVC = windowScene.windows.first(where: { $0.isKeyWindow })?.rootViewController  as? UITabBarController {
                        rootVC.selectedIndex = 0
                        (rootVC as! BTEBaseTabBarController).basetabbar.la.image = UIImage.init(named: "gwerger432323232")
                        (rootVC as! BTEBaseTabBarController).basetabbar.ed.image = UIImage.init(named: "fwef32323232er23")
                    }
                        }
                    } else {
                        list.empty.hidden()
                    }
            
            list.reloadData()
        }
    }
    
    var OrderTypes: OrderType!
    
    fileprivate let server = BTEProductToolNetServer()
    
    var refreshfunc: UIRefreshControl!
    
    let list = BTEBaseTableView.init(frame: .zero, style: .plain)
    
    init(OrderT: OrderType!) {
        self.OrderTypes = OrderT
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        refreshfunc = UIRefreshControl()
        refreshfunc.addTarget(self, action: #selector(loadInfoaction), for: .valueChanged)
        list.refreshControl = refreshfunc
        
        
        list.showsHorizontalScrollIndicator = false
        list.backgroundColor = .clear
        view.addSubview(list)
        list.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        list.delegate = self
        list.dataSource = self
        list.separatorStyle = .none
        
        list.register(BTEOrderTableViewCell.self, forCellReuseIdentifier: BTEOrderTableViewCell.indetification)
    }
    
    
    
    @objc func loadInfoaction(){
        BTEHUD.shared.showLoader(on: view)
        server.penalosa(data: ["unextremeness":"\(OrderTypes.rawValue)"]) {[weak self] result in
            switch result {
            case .success(let success):
                self?.refreshfunc.endRefreshing()
                BTEHUD.shared.hide()
                self?.model = success?.sidelingwise?.vincents
                break
            case .failure(let failure):
                self?.refreshfunc.endRefreshing()
                BTEHUD.shared.hide()
                break
            }
        }
    }


}




extension BTEOrderSubViewController: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (model ?? []).count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: BTEOrderTableViewCell.indetification, for: indexPath) as? BTEOrderTableViewCell else {
            return UITableViewCell()
        }
        
        if let m = model?[indexPath.row] {
            cell.ttittt.text = m.cuspid
            cell.timage.sd_setImage(with: URL.init(string: m.butyrins!))
            cell.button.setTitle(title: m.allergin ?? "")
            
            var lats: UIView?
            cell.listbox.subviews.forEach({$0.removeFromSuperview()})
            if let lists = m.flinter {
                lists.enumerated().forEach { item in
                    let vi = OrderListView.init()
                    vi.lab.text = item.element.aftermath
                    vi.rihgtl.text = item.element.celtophobe
                    cell.listbox.addSubview(vi)
                    vi.snp.makeConstraints { make in
                        make.left.right.equalToSuperview()
                        if lats == nil {
                            make.top.equalToSuperview()
                        } else {
                            make.top.equalTo(lats!.snp.bottom).offset(6)
                        }
                        
                        if item.offset == lists.count - 1 {
                            make.bottom.equalToSuperview().offset(-6)
                        }
                    }
                    lats = vi
                }
            }
            
            if let pro = m.catalyses, pro.count > 0 {
                cell.proview.isHidden = false
                cell.p1.text = pro
                cell.listbox.snp.remakeConstraints { make in
                    make.left.right.equalToSuperview().inset(26)
                    make.top.equalTo(cell.topBox.snp.bottom).offset(10)
                }
                
                cell.proview.snp.remakeConstraints { make in
                    make.left.right.equalToSuperview().inset(26)
                    make.top.equalTo(cell.listbox.snp.bottom).offset(10)
                    make.bottom.equalToSuperview().offset(-10)
                }
            } else {
                
                cell.proview.isHidden = true
                
                cell.proview.snp.remakeConstraints{ make in
                    make.left.right.equalToSuperview().inset(26)
                    make.top.equalTo(cell.listbox.snp.bottom).offset(10)
                }
                
                cell.listbox.snp.remakeConstraints { make in
                    make.left.right.equalToSuperview().inset(26)
                    make.top.equalTo(cell.topBox.snp.bottom).offset(10)
                    make.bottom.equalToSuperview().offset(-12)
                }
            }
        }
        
        let pro = UITapGestureRecognizer.init(target: self, action: #selector(clickPros))
        cell.proview.isUserInteractionEnabled = true
        cell.proview.addGestureRecognizer(pro)
        cell.proview.tag = indexPath.row
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let m = model?[indexPath.row] {
            clickItem?(m.lina ?? "")
        }
    }
    
    @objc func clickPros(_ t: UITapGestureRecognizer){
        if let v = t.view {
            if let m = model?[v.tag] {
                clickItem?(m.scallom ?? "")
            }
        }
    }
    
}
